package com.mxpio.erp.technology.controller;

import com.mxpio.erp.common.enums.OrderStatusEnums;
import com.mxpio.erp.common.technology.entity.BomInfo;
import com.mxpio.erp.common.technology.entity.BomInfoLine;
import com.mxpio.erp.common.technology.service.BomInfoLineService;
import com.mxpio.erp.common.technology.service.BomInfoService;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.CriteriaUtils;
import com.mxpioframework.jpa.query.Operator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.List;

@Api(value = "BomInfoController", tags = { "Bom接口" })
@RestController
@RequestMapping("/erp/tech/bom/")
public class BomInfoController {

    @Autowired
    private BomInfoService bomInfoService;

    @Autowired
    private BomInfoLineService bomInfoLineService;

    @GetMapping("list")
    @ApiOperation(value = "Bom列表", notes = "获取Bom列表（无分页）", httpMethod = "GET")
    public Result<List<BomInfo>> list(String criteria) throws UnsupportedEncodingException {
        Criteria c = CriteriaUtils.json2Criteria(criteria);
        List<BomInfo> bomInfos = bomInfoService.list(BomInfo.class, c);
        return Result.OK(bomInfos);
    }

    @GetMapping("page")
    @ApiOperation(value = "Bom列表", notes = "获取Bom列表（分页）", httpMethod = "GET")
    public Result<Page<BomInfo>> page(String criteria, Integer pageSize, Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Criteria c = CriteriaUtils.json2Criteria(criteria);
        Page<BomInfo> bomInfos = bomInfoService.listPage(BomInfo.class, page, c);
        return Result.OK(bomInfos);
    }


    @GetMapping("list/{bizCode}")
    @ApiOperation(value = "根据bizCode获取Bom", notes = "根据bizCode获取Bom", httpMethod = "GET")
    public Result<BomInfo> getById(@PathVariable(name = "bizCode", required = true) String bizCode) {
        BomInfo bomInfo = bomInfoService.getById(BomInfo.class, bizCode);
        return Result.OK(bomInfo);
    }

    @RequestMapping("save")
    @ApiOperation(value = "保存Bom", notes = "保存Bom")
    public Result<BomInfo> save(@RequestBody BomInfo bomInfo) {
        if(StringUtils.isBlank(bomInfo.getVersion())){
            bomInfo.setVersion("V1.0");
        }
        bomInfoService.save(bomInfo,new SmartCrudPolicyAdapter(){
            @Override
            public boolean beforeInsert(CrudContext context) {
                Object o = context.getEntity();
                if(o instanceof BomInfoLine){
                    BomInfo bom = context.getParent();
                    ((BomInfoLine) o).setBizNo(bomInfo.getBizNo());
                }
                return true;
            }
        });
        return Result.OK(bomInfo);
    }

    @DeleteMapping("remove/{bizNos}")
    @ApiOperation(value = "根据bizNo删除Bom", notes = "删除Bom", httpMethod = "DELETE")
    @Transactional(readOnly = false)
    public Result<BomInfo> remove(@ApiParam(name="业务单号，多个单号用英文逗号分隔") @PathVariable(name = "bizNos", required = true) String bizNos) {
        String[] bizNo = bizNos.split(",");
        for(String key : bizNo){
            Criteria c = Criteria.create().addCriterion("bizNo", Operator.EQ, key);
            bomInfoLineService.removeBatch(BomInfoLine.class, c);
            bomInfoService.delete(BomInfo.class, key);
        }
        return Result.OK();
    }

    @PutMapping("submit/{bizNo}")
    @ApiOperation(value = "提交Bom", notes = "提交Bom", httpMethod = "PUT")
    public Result<BomInfo> submit(@ApiParam(name="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
        BomInfo bomInfo = bomInfoService.getById(BomInfo.class,bizNo);
        if(bomInfo.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode())){
            bomInfo.setVersion(bomInfoService.increaseVersion(bomInfo.getVersion()));
            return bomInfoService.updateBpmnStatus(bomInfo, OrderStatusEnums.BpmnStatus.AUDITING);
        }else {
            return Result.error("非开立状态不可提交");
        }
    }

    @PutMapping("audit/{bizNo}")
    @ApiOperation(value = "审核Bom", notes = "审核Bom", httpMethod = "PUT")
    public Result<BomInfo> audit(@ApiParam(name="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
        BomInfo bomInfo = bomInfoService.getById(BomInfo.class,bizNo);
        if(bomInfo.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())){
            return bomInfoService.updateBpmnStatus(bomInfo, OrderStatusEnums.BpmnStatus.AUDITED);
        }else {
            return Result.error("非审核中状态不可审核");
        }
    }

    @PutMapping("abandon/{bizNo}")
    @ApiOperation(value = "弃审Bom", notes = "弃审Bom", httpMethod = "PUT")
    public Result<BomInfo> abandon(@ApiParam(name="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
        BomInfo bomInfo = bomInfoService.getById(BomInfo.class,bizNo);
        if(bomInfo.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())||bomInfo.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode())){
            return bomInfoService.updateBpmnStatus(bomInfo, OrderStatusEnums.BpmnStatus.CREATE);
        }else{
            return Result.error("非审核中、已审核状态不可审核");
        }
    }

    @PutMapping("use/{bizNo}")
    @ApiOperation(value = "使用Bom", notes = "使用Bom", httpMethod = "PUT")
    public Result<BomInfo> use(@ApiParam(name="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
        BomInfo bomInfo = bomInfoService.getById(BomInfo.class,bizNo);
        //使用
        bomInfo.setUseStatus("01");
        bomInfoService.save(bomInfo);
        return Result.OK();
    }
}
